package com.youmingxing.activity.selfInfo;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.youmingxing.R;
import com.youmingxing.activity.BaseActivity;
import com.youmingxing.activity.RankListActivity;
import com.youmingxing.adpter.ContentListAdapter;
import com.youmingxing.adpter.RecyclerViewAdapter.RankRecyclerViewAdapter;
import com.youmingxing.adpter.RecyclerViewAdapter.VoteRecyclerViewAdapter;
import com.youmingxing.bean.AuditionResultFromId;
import com.youmingxing.bean.Content;
import com.youmingxing.bean.selfinfo.AuditionRank;
import com.youmingxing.data.GlobalDataManager;
import com.youmingxing.dialog.ShareDialog;
import com.youmingxing.network.AllStarApi;
import com.youmingxing.network.BaseJsonHandler;
import com.youmingxing.utils.TimeUtils;
import com.youmingxing.view.DialogManager;
import com.youmingxing.view.RefreshListView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import jp.wasabeef.glide.transformations.CropCircleTransformation;


/**
 * Created by JHS on 2015/9/17
 * Edited by ChenZhixi
 * 我的海选 正在进行中
 */
public class MyAuditionGoingActivity extends BaseActivity implements View.OnClickListener {

    List<Content> list = new ArrayList<>();
    List<AuditionRank> rankList = new ArrayList<>();
    private RefreshListView listView;
    View headView;
    private AuditionResultFromId resultFromId;

    private RecyclerView voteLayout;
    private RecyclerView rankLayout;
    private RelativeLayout voteBigLayout;

    private int mark = 1;
    private ContentListAdapter adapter;
    private int id;

    public static final String EXTRAS_ID = "id";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BaseSetContentView(R.layout.activity_myauditions);
        listView = (RefreshListView) findViewById(R.id.list_view);
        Bundle bundle = getIntent().getExtras();
        id = bundle.getInt(EXTRAS_ID);
        DialogManager.showDialog(this, "加载中");
        AllStarApi.showAudition(id, resultHandler);
    }


    @Override
    public void onErrorClick() {
        AllStarApi.showAudition(id, resultHandler);
    }

    BaseJsonHandler resultHandler = new BaseJsonHandler(this) {
        @Override
        public void onSuccessWithData(JSONObject response) {
            showErrorPage(false);
            JSONObject data = response.optJSONObject("data");
            resultFromId = new AuditionResultFromId(data);
            if (headView == null) {
                headView = getLayoutInflater().inflate(R.layout.activity_myauditions_top, null);
                listView.addHeaderView(headView);
                adapter = new ContentListAdapter(MyAuditionGoingActivity.this);
                listView.setAdapter(adapter);
            }
            boolean isMine = GlobalDataManager.userId == resultFromId.u_id;
            initTopView(headView, isMine);
            AllStarApi.getAuditionRank(resultFromId.movie_id, resultFromId.category_id, 1, rankHandler);
            AllStarApi.getUserVoters(resultFromId.u_id, 1, voteHandler);
            mark = 1;
            AllStarApi.getUserContents(resultFromId.u_id, mark, workHandler);
            listView.setOnLoadMoreListener(new RefreshListView.OnLoadMoreListener() {
                @Override
                public void onLoadMore() {
                    AllStarApi.getUserContents(resultFromId.u_id, mark, workHandler);
                }
            });
            DialogManager.dismissDialog();
        }

        @Override
        public void onFail(int statusCode, String statusText) {
            super.onFail(statusCode, statusText);
            showErrorPage(true);
        }
    };

    BaseJsonHandler rankHandler = new BaseJsonHandler(this) {
        @Override
        public void onSuccessWithData(JSONObject response) {
            JSONArray data = response.optJSONArray("data");
            if (data.length() >= 20) {
                findViewById(R.id.other_player_more).setVisibility(View.VISIBLE);
            }
            rankList.clear();
            for (int i = 0; i < data.length(); i++) {
                AuditionRank rank = new AuditionRank(data.optJSONObject(i));
                rankList.add(rank);
            }

            RankRecyclerViewAdapter adapter = new RankRecyclerViewAdapter(MyAuditionGoingActivity
                    .this, rankList);
            adapter.setOnItemClickListener(new RankRecyclerViewAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    Intent intent = new Intent(MyAuditionGoingActivity.this,
                            PersonalInfoActivity.class);
                    intent.putExtra("u_id", rankList.get(position).u_id);
                    MyAuditionGoingActivity.this.startActivity(intent);
                }
            });
            rankLayout.setAdapter(adapter);

        }
    };

    BaseJsonHandler voteHandler = new BaseJsonHandler(this) {
        @Override
        public void onSuccessWithData(JSONObject response) {
            final JSONArray data = response.optJSONArray("data");
            if (data.length() >= 20) {
                findViewById(R.id.buy_tickets_ranking_more).setVisibility(View.VISIBLE);
            } else if (data.length() == 0) {
                voteBigLayout.setVisibility(View.GONE);
                findViewById(R.id.view14).setVisibility(View.GONE);
                return;
            }
            VoteRecyclerViewAdapter adapter = new VoteRecyclerViewAdapter(MyAuditionGoingActivity
                    .this, data);
            adapter.setOnItemClickListener(new VoteRecyclerViewAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    Intent intent = new Intent(MyAuditionGoingActivity.this, PersonalInfoActivity.class);
                    intent.putExtra("u_id", data.optJSONObject(position).optInt("id"));
                    startActivity(intent);
                }
            });
            voteLayout.setAdapter(adapter);

        }
    };

    BaseJsonHandler workHandler = new BaseJsonHandler(this) {
        @Override
        public void onSuccessWithData(JSONObject response) {
            listView.endLoadMore();
            JSONArray data = response.optJSONArray("data");
            if (mark == 1) {
                list = new ArrayList<>();
                if (data.length() == 0) {
                    listView.noData("还没有作品哦");
                }
            }
            if (data.length() != 0) {

                for (int i = 0; i < data.length(); i++) {
                    Content content = new Content(data.optJSONObject(i));
                    content.u_apply_id = -1;
                    list.add(content);
                }
                adapter.setData(list);
                adapter.notifyDataSetChanged();
            } else {
                listView.noMoreData();
            }
            mark++;
        }
    };


    private void initTopView(View view, boolean isMine) {
        setLeftAndrightTv(true, true, false, R.string.share_audition, null, this, null);
        TextView works = (TextView) view.findViewById(R.id.my_works);
        if (isMine) {
            setTopbarName(R.string.auditions_title);
            works.setText("我的作品");
        } else {
            setTopbarName(R.string.other_audition_title);
            works.setText("TA的作品");
        }
        ImageView headImage = (ImageView) view.findViewById(R.id.user_icon);
        TextView userName = (TextView) view.findViewById(R.id.user_name);
        ImageView isVerified = (ImageView) view.findViewById(R.id.is_auth);
        RelativeLayout verifyLayout = (RelativeLayout) view.findViewById(R.id.not_certificated_layout);
        TextView resultTickets = (TextView) view.findViewById(R.id.my_tickets_num1);
        TextView resultRanking = (TextView) view.findViewById(R.id.my_ranking_num1);
        TextView motto = (TextView) view.findViewById(R.id.user_des);
        TextView quit = (TextView) view.findViewById(R.id.quit_audition);
        Button sendTicket = (Button) view.findViewById(R.id.send_tickets);
        TextView moreOther = (TextView) view.findViewById(R.id.other_player_more);
        TextView moreFans = (TextView) view.findViewById(R.id.buy_tickets_ranking_more);
        voteLayout = (RecyclerView) view.findViewById(R.id.buy_tickets_ranking_listview);
        rankLayout = (RecyclerView) view.findViewById(R.id.other_player_ranking);

        LinearLayoutManager manager = new LinearLayoutManager(MyAuditionGoingActivity.this);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        LinearLayoutManager manager2 = new LinearLayoutManager(MyAuditionGoingActivity.this);
        manager2.setOrientation(LinearLayoutManager.HORIZONTAL);
        rankLayout.setLayoutManager(manager);
        voteLayout.setLayoutManager(manager2);

        voteBigLayout = (RelativeLayout) view.findViewById(R.id.ticket_send_rank_layout);
        Glide.with(MyAuditionGoingActivity.this).load(resultFromId.u_headimg)
                .placeholder(R.drawable.default_avatar).error(R.drawable.default_avatar)
                .bitmapTransform(new CropCircleTransformation(
                        MyAuditionGoingActivity.this)).crossFade().into(headImage);
        userName.setText(resultFromId.u_name);
        isVerified.setVisibility(resultFromId.real_auth_status == 3 ? View.VISIBLE : View.GONE);
        resultTickets.setText(resultFromId.votes + "");
        resultRanking.setText(resultFromId.rank + "");
        motto.setText(resultFromId.motto);
        if (resultFromId.u_id == GlobalDataManager.userId) {
            quit.setVisibility(View.VISIBLE);
            verifyLayout.setVisibility(resultFromId.real_auth_status == 3 ? View.GONE : View.VISIBLE);
        }
        verifyLayout.setOnClickListener(this);
        quit.setOnClickListener(this);
        sendTicket.setOnClickListener(this);
        moreOther.setOnClickListener(this);
        moreFans.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.not_certificated_layout:
                switch (resultFromId.real_auth_status) {
                    case 0:
                        intent.setClass(MyAuditionGoingActivity.this, CertificationActivity.class);
                        startActivity(intent);
                        break;
                    case 1:
                    case 2:
                        intent.setClass(MyAuditionGoingActivity.this, CertificationingActivity.class);
                        startActivity(intent);
                        break;
                    case 3:
                        showToast("您已通过认证!");
                        break;
                }
                break;
            case R.id.quit_audition:
                AlertDialog.Builder builder = new AlertDialog.Builder(MyAuditionGoingActivity.this);
                builder.setTitle(R.string.quit_audition_title).setMessage(R.string
                        .quit_audition_message)
                        .setPositiveButton("是", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                showDialog("正在提交");
                                AllStarApi.quitAudition(id, new BaseJsonHandler(MyAuditionGoingActivity.this) {
                                    @Override
                                    public void onSuccessWithData(JSONObject response) {
                                        showToast(R.string.quit_audition_success);
                                        finish();
                                    }
                                });
                            }
                        }).setNegativeButton("否", null).show();
                break;
            case R.id.send_tickets:
                showDialog("正在提交");
                AllStarApi.vote(id, 1, new BaseJsonHandler(this) {
                    @Override
                    public void onSuccessWithData(JSONObject response) {
                        int result = response.optJSONObject("data").optInt("result");
                        switch (result) {
                            case 1:
                                showToast("加油成功");
                                AllStarApi.showAudition(id, resultHandler);
                                break;
                            case 0:
                                showToast("系统错误");
                                break;
                            case 2:
                                long time = response.optJSONObject("data").optLong("gen_duetime");
                                AlertDialog.Builder builder = new AlertDialog.Builder
                                        (MyAuditionGoingActivity.this);
                                builder.setCancelable(false).setTitle("您的加油票不足1张").setMessage
                                        (TimeUtils.parseSecondToString(time) + "后,您将得到一张新票")
                                        .setPositiveButton("确定", null).show();
                                break;
                        }
                    }
                });
                break;
            case R.id.other_player_more:
                intent = new Intent(MyAuditionGoingActivity.this, RankListActivity.class);
                intent.putExtra("movie_id", resultFromId.movie_id);
                intent.putExtra("category_id", resultFromId.category_id);
                startActivity(intent);
                break;
            case R.id.buy_tickets_ranking_more:
                intent = new Intent(MyAuditionGoingActivity.this, FansActivity.class);
                intent.putExtra("type", 1);
                intent.putExtra("user_id", resultFromId.u_id);
                startActivity(intent);
                break;
            case R.id.header_tv_right:
                showShareDialog();
                break;
        }
    }

    private void showShareDialog() {
        Intent intent = new Intent(this, ShareDialog.class);
        intent.putExtra("id", resultFromId.id);
        intent.putExtra("entrance", 2);
        startActivity(intent);
    }
}